#include <algorithm>
#include <cmath>
#include <iostream>
#define LL long long
using namespace std;

const int kMaxN = 110;
const int kMaxM = 110;
const LL kInf64 = 1e18;

LL a[kMaxN][kMaxM], f[kMaxN][kMaxM];
LL a00[kMaxN * kMaxM];

int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int T;
  for (cin >> T; T; T--) {
    int n, m, tot = 0;
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> a[i][j];
        if (a[i][j] - i - j <= a[0][0]) {
          a00[tot++] = a[i][j] - i - j;
        }
      }
    }
    sort(a00, a00 + tot);
    tot = unique(a00, a00 + tot) - a00;

    LL ans = kInf64;
    for (int t = 0; t < tot; t++) {
      LL need = a00[t];

      for (int i = 0; i < n; i++) {
        fill(f[i], f[i] + m, kInf64);
      }
      f[0][0] = abs(need - a[0][0]);
      for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
          if (i + 1 < n && a[i + 1][j] >= need + i + j + 1) {
            f[i + 1][j] = min(f[i + 1][j], f[i][j] + a[i + 1][j] - (need + i + 1 + j));
          }
          if (j + 1 < m && a[i][j + 1] >= need + i + j + 1) {
            f[i][j + 1] = min(f[i][j + 1], f[i][j] + a[i][j + 1] - (need + i + j + 1));
          }
        }
      }
      ans = min(f[n - 1][m - 1], ans);
    }
    cout << ans << "\n";
  }
  return 0;
}
